<template>
  <el-tree
    :data="data"
    :props="defaultProps"
    @node-click="handleNodeClick"
    :expand-on-click-node="false"
  ></el-tree>
</template>
<script>
export default {
  data() {
    return {
      data: [],
      defaultProps: {
        children: 'children',
        label: 'content',
      },
    };
  },
  props: ['root'],
  watch: {
    root(val) {
      if (val) {
        this.generateData();
      }
    },
  },
  methods: {
    handleNodeClick(data) {
      this.root.scrollTo(0, data.top);
    },
    generateData() {
      let tagArray = [];
      Array.from(this.root.querySelectorAll('h1,h2,h3,h4,h5')).forEach((item, index) => {
        tagArray.push({
          name: item.tagName,
          top: item.offsetTop - this.root.offsetTop,
          content: item.innerText,
        });
      });
      let root = [];
      let last = null;
      while (tagArray.length > 0) {
        let current = tagArray.shift();
        if (root.length === 0) {
          current.parent = root;
          root.push(current);
          last = root[root.length - 1];
        } else {
          if (current.name !== last.name) {
            let target = last;
            let isParent = false;
            while (target.parent) {
              target = target.parent;
              console.log(target);
              if (target.name === current.name) {
                target.parent.push(current);
                last = current;
                isParent = true;
                break;
              }
            }
            if (!isParent) {
              current.parent = last;
              if (!last.children) last.children = [];
              last.children.push(current);
              last = last.children[last.children.length - 1];
            }
          } else {
            current.parent = last.parent;
            last.parent.children.push(current);
            last = current;
          }
        }
      }
      this.data = root;
    },
  },
};
</script>